﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TheOutfield.UmbExt.UniversalMediaPicker.Interfaces;
using umbraco.cms.businesslogic.datatype;
using umbraco.BusinessLogic.Utils;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public class UniversalMediaPickerProviderFactory
    {
        public static readonly Dictionary<string, Type> Providers = new Dictionary<string, Type>();

        static UniversalMediaPickerProviderFactory()
        {
            RegisterProviders();
        }

        private static void RegisterProviders()
        {
            var types = TypeFinder.FindClassesOfType<IProvider>(true);
            foreach (var t in types)
            {
                var typeInstance = Activator.CreateInstance(t) as IProvider;
                if (typeInstance != null)
                {
                    Providers.Add(typeInstance.Alias, t);
                }
            }
        }

        public static IProvider CreateProvider(string providerAlias, string config)
        {
            return Activator.CreateInstance(Providers[providerAlias], config) as IProvider;
        }

        public static IProvider GetProvider(int dataTypeDefinitionId)
        {
            var dtd = DataTypeDefinition.GetDataTypeDefinition(dataTypeDefinitionId);
            if (dtd == null)
                return null;

            var dt = dtd.DataType as UniversalMediaPickerDataType;
            if (dt == null)
                return null;

            var p = CreateProvider(dt.Config.ProviderAlias, dt.Config.ProviderConfig);

            return p;
        }

        public static T GetProvider<T>(int dataTypeDefinitionId) where T : class, IProvider
        {
            return GetProvider(dataTypeDefinitionId) as T;
        }
    }
}